<template>
  <a-modal 
    v-model:visible="visible" 
    :title="isEdit ? '修改子项目' : '新增子项目'" 
    :width="500" 
    @ok="handleOk" 
    @cancel="handleCancel" 
    centered 
    :bodyStyle="{ padding: '32px 32px 24px 32px' }" 
    :destroyOnClose="true"
    :maskClosable="false"
    :keyboard="false"
  >
    <a-form :label-col="{span: 6}" :wrapper-col="{span: 16}" style="margin-top: 8px;">
      <a-form-item label="所属项目" style="margin-bottom: 24px;">
        <a-input v-model:value="form.projectName" readonly />
      </a-form-item>
      <a-form-item label="项目剩余金额" style="margin-bottom: 24px;">
        <a-input :value="formattedRemainingAmount" readonly />
      </a-form-item>
      <a-form-item label="子项目名称" style="margin-bottom: 24px;">
        <a-input v-model:value="form.subProjectName" placeholder="请输入子项目名称" />
      </a-form-item>
      <a-form-item label="子项目内容" style="margin-bottom: 24px;">
        <a-input v-model:value="form.subProjectContent" placeholder="请输入子项目内容" />
      </a-form-item>
      <a-form-item label="子项目金额" style="margin-bottom: 24px;">
        <template v-if="isEdit">
          <a-input :value="formatAmount(form.subProjectAmount)" readonly />
        </template>
        <template v-else>
          <a-input-number 
            v-model:value="form.subProjectAmount" 
            placeholder="请输入子项目金额" 
            style="width: 100%" 
            :precision="2"
            :min="0"
            @change="validateAmount"
          />
        </template>
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script setup>
import { ref, watch, onMounted, computed, onBeforeUnmount } from 'vue'
import { addSubProject, updateSubProject, getProjectRemainingAmount } from '../Projects.api'
import { message } from 'ant-design-vue'

const props = defineProps({
  projectId: String,
  projectName: String,
  isEdit: {
    type: Boolean,
    default: false
  },
  editData: {
    type: Object,
    default: () => ({})
  }
})

const emit = defineEmits(['success', 'close'])
const visible = ref(true)
const remainingAmount = ref(0)
const form = ref({
  id: '',
  projectId: props.projectId,
  projectName: props.projectName,
  subProjectName: '',
  subProjectContent: '',
  subProjectAmount: 0 // Added subProjectAmount field with default value 0
})

// 保存原始金额
const originalAmount = ref(0);

// 格式化的剩余金额
const formattedRemainingAmount = computed(() => {
  return formatAmount(remainingAmount.value);
})

// 格式化金额函数
function formatAmount(amount) {
  if (amount === null || amount === undefined) {
    return '0.00';
  }
  return parseFloat(amount).toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
}

// 监听项目ID和名称变化
watch(() => props.projectId, (val) => { 
  if (val) {
    form.value.projectId = val;
    fetchRemainingAmount(val);
  }
}, { immediate: true })

watch(() => props.projectName, (val) => { 
  if (val) {
    form.value.projectName = val;
  }
}, { immediate: true })

// 监听编辑数据变化
watch(() => props.editData, (val) => {
  if (props.isEdit && val && Object.keys(val).length > 0) {
    form.value = {
      id: val.id || '',
      projectId: val.projectId || props.projectId || '',
      projectName: props.projectName || '',
      subProjectName: val.subProjectName || '',
      subProjectContent: val.subProjectContent || '',
      subProjectAmount: val.subProjectAmount || 0
    }
    // 保存原始金额，用于编辑时提交
    originalAmount.value = val.subProjectAmount || 0;
  }
}, { immediate: true })

// 获取项目剩余金额
async function fetchRemainingAmount(projectId) {
  if (!projectId) return;
  
  try {
    console.log("开始获取项目剩余金额, projectId:", projectId);
    const response = await getProjectRemainingAmount(projectId);
    
    // 如果响应是字符串，直接尝试转换为数字
    if (response !== null && response !== undefined) {
      if (typeof response === 'string') {
        // 尝试直接将字符串转换为数字
        const numValue = parseFloat(response);
        if (!isNaN(numValue)) {
          remainingAmount.value = numValue;
          return;
        }
      } else if (typeof response === 'number') {
        // 如果直接返回数字
        remainingAmount.value = response;
        return;
      }
      
      // 如果不是简单的数字，尝试其他格式
      // 将响应转换为字符串
      const responseStr = response.toString();
      
      // 尝试多种正则表达式提取数字
      const patterns = [
        /(-?\d+\.?\d*)/,                  // 普通数字
        /remainingAmount=(-?\d+\.?\d*)/,  // 旧格式
        /"remainingAmount":(-?\d+\.?\d*)/ // JSON格式
      ];
      
      let matched = false;
      for (const regex of patterns) {
        const match = responseStr.match(regex);
        if (match && match[1]) {
          // 提取到数值并转换为浮点数
          remainingAmount.value = parseFloat(match[1]);
          matched = true;
          break;
        }
      }
      
      if (!matched) {
        remainingAmount.value = 0;
      }
    } else {
      remainingAmount.value = 0;
    }
  } catch (error) {
    console.error('获取项目剩余金额失败:', error);
    remainingAmount.value = 0;
  }
}

// 验证金额
function validateAmount(value) {
  if (value < 0) {
    message.error('子项目金额不能小于0');
    // 重置为0
    form.value.subProjectAmount = 0;
    return false;
  }
  
  if (value > remainingAmount.value) {
    message.warning(`金额超出项目剩余金额 ${formattedRemainingAmount.value}`);
  }
  
  return true;
}

async function handleOk() {
  // Simple validation
  if (!form.value.subProjectName) {
    message.error('子项目名称不能为空');
    return;
  }

  // 验证金额
  if (!props.isEdit) {
    if (form.value.subProjectAmount < 0) {
      message.error('子项目金额不能小于0');
      return;
    }
    
    if (form.value.subProjectAmount > remainingAmount.value) {
      message.error(`金额超出项目剩余金额 ${formattedRemainingAmount.value}`);
      return;
    }
  }

  try {
    if (props.isEdit) {
      // 编辑模式下，使用原始金额
      const updateData = {
        id: form.value.id,
        projectId: form.value.projectId,
        subProjectName: form.value.subProjectName,
        subProjectContent: form.value.subProjectContent,
        subProjectAmount: originalAmount.value // 使用原始金额
      };
      await updateSubProject(updateData);
      message.success('修改成功');
    } else {
      await addSubProject(form.value);
      message.success('添加成功');
    }
    
    // 先通知成功，再关闭模态框
    emit('success');
    
    // 延迟关闭，确保数据已经处理完毕
    setTimeout(() => {
      visible.value = false;
      emit('close');
    }, 100);
  } catch (e) {
    console.error('操作失败:', e);
    message.error(props.isEdit ? '修改失败' : '添加失败');
  }
}

function handleCancel() {
  visible.value = false;
  setTimeout(() => {
    emit('close');
  }, 100);
}

// 组件挂载时获取剩余金额
onMounted(() => {
  if (props.projectId) {
    fetchRemainingAmount(props.projectId);
  }
})

// 组件销毁前清理
onBeforeUnmount(() => {
  // 确保组件被正确销毁
  visible.value = false;
})
</script>

<style scoped>
/* 增加表单整体的空白和美观 */
:deep(.ant-modal-content) {
  border-radius: 10px;
}
:deep(.ant-modal-header) {
  border-radius: 10px 10px 0 0;
}
:deep(.ant-modal-body) {
  background: #fafbfc;
}
:deep(.ant-form-item) {
  margin-bottom: 24px !important;
}
:deep(.ant-input) {
  padding: 8px 12px;
  font-size: 15px;
}
</style> 